package cn.kgc.kgcesproduct.util;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author geQiang
 * @version 1.0
 * @date 2019/4/14
 * @description cn.kgc.kgcesproduct.util
 */
@Component
public class ELSUtil {
    private TransportClient transportClient;
    private static final String IP = "192.168.79.140";
    private static final int PORT = 9300;

    /**
     * 获得连接
     * @return
     */
    public TransportClient getTransportClient() {
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name", "elasticsearch-application")
                    .build();
            transportClient = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName(IP), PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        System.out.println("连接成功！");
        return transportClient;
    }

    /**
     * 关闭资源
     *
     * @param transportClient
     */
    public void close(TransportClient transportClient) {
        if (transportClient != null) {
            transportClient.close();
        }
    }
}
